<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增用户"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      ref="addFormRef"
      :model="newUser"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="newUser.username" autocomplete="username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="newUser.password" autocomplete="new-password" placeholder="请输入密码" type="password" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="newUser.email" placeholder="请输入邮箱" type="email" />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="newUser.role" placeholder="请选择角色">
          <el-option label="管理员" value="admin" />
          <el-option label="普通用户" value="user" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="newUser.status" placeholder="请选择状态">
          <el-option label="激活" value="1" />
          <el-option label="未激活" value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from 'vue';
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElDialog, ElMessage } from 'element-plus';
import request from '@/utils/request';

interface User {
  id: number|undefined;
  username: string;
  password: string;
  email: string;
  role: string;
  status: number|undefined;
}

const props = defineProps<{
  visible: boolean;
}>();

const emits = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'success'): void;
}>();

const dialogVisible = ref<boolean>(props.visible);
const newUser = ref<User>({ id: undefined, username: '',password:'', email: '', role: '', status: undefined });
const addFormRef = ref<InstanceType<typeof ElForm>>();

const rules = ref<Record<string, any>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
});

const submitForm = async () => {
  if (!addFormRef.value) return;
  try {
    await addFormRef.value.validate();
    // 发送创建用户请求
    await request.post('/users', newUser.value);
    ElMessage.success('用户创建成功');
    emits('success');
    dialogVisible.value = false;
    resetForm();
  } catch (error) {
    ElMessage.error('用户创建失败，请重试');
    console.error('创建用户失败:', error);
  }
};

const resetForm = () => {
  newUser.value = { id: undefined, username: '',password:'', email: '', role: '', status: undefined };
  addFormRef.value?.resetFields();
};

const handleClose = () => {
  emits('update:visible', false);
  resetForm();
};

// 监听visible prop变化
watch(() => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  }
);

// 向父组件发送visible更新事件
watch(dialogVisible,
  (newVal) => {
    emits('update:visible', newVal);
  }
);
</script>